/**
 * 番茄钟数据模型
 * 处理番茄钟相关的数据库操作
 */
const { query } = require('../config/database');

const pomodoroModel = {
  /**
   * 开始一个新的番茄钟会话
   * @param {Object} pomodoroData - 番茄钟数据
   * @returns {Promise<Object>} 创建的番茄钟记录
   */
  start: async (pomodoroData) => {
    const sql = `
      INSERT INTO pomodoro_records 
      (user_id, task_id, start_time, duration, status) 
      VALUES (?, ?, ?, ?, ?)
    `;
    
    const now = new Date();
    
    const result = await query(sql, [
      pomodoroData.user_id,
      pomodoroData.task_id || null,
      pomodoroData.start_time || now,
      pomodoroData.duration || 25, // 默认25分钟
      0 // 状态：进行中
    ]);
    
    return { 
      id: result.insertId, 
      ...pomodoroData, 
      start_time: pomodoroData.start_time || now,
      status: 0
    };
  },

  /**
   * 结束番茄钟会话
   * @param {number} id - 番茄钟ID
   * @param {number} userId - 用户ID
   * @param {number} status - 结束状态 (1-完成, 2-中断)
   * @returns {Promise<boolean>} 更新是否成功
   */
  end: async (id, userId, status) => {
    const now = new Date();
    const sql = `
      UPDATE pomodoro_records 
      SET end_time = ?, status = ? 
      WHERE id = ? AND user_id = ? AND status = 0
    `;
    
    const result = await query(sql, [now, status, id, userId]);
    return result.affectedRows > 0;
  },

  /**
   * 获取用户的番茄钟历史记录
   * @param {number} userId - 用户ID
   * @param {Object} filters - 过滤条件
   * @returns {Promise<Array>} 番茄钟记录列表
   */
  getHistory: async (userId, filters = {}) => {
    let sql = `
      SELECT p.*, t.title as task_title 
      FROM pomodoro_records p
      LEFT JOIN tasks t ON p.task_id = t.id
      WHERE p.user_id = ?
    `;
    
    const queryParams = [userId];
    
    // 日期过滤
    if (filters.date) {
      const date = new Date(filters.date);
      const dateStr = date.toISOString().split('T')[0];
      sql += ' AND DATE(p.start_time) = ?';
      queryParams.push(dateStr);
    }
    
    // 状态过滤
    if (filters.status !== undefined) {
      sql += ' AND p.status = ?';
      queryParams.push(filters.status);
    }
    
    // 按任务过滤
    if (filters.task_id) {
      sql += ' AND p.task_id = ?';
      queryParams.push(filters.task_id);
    }
    
    // 排序
    sql += ' ORDER BY p.start_time DESC';
    
    // 分页
    if (filters.limit) {
      sql += ' LIMIT ?';
      queryParams.push(parseInt(filters.limit));
      
      if (filters.offset) {
        sql += ' OFFSET ?';
        queryParams.push(parseInt(filters.offset));
      }
    }
    
    return await query(sql, queryParams);
  },

  /**
   * 获取番茄钟统计信息
   * @param {number} userId - 用户ID
   * @param {string} period - 统计周期 (day, week, month)
   * @returns {Promise<Object>} 统计信息
   */
  getStatistics: async (userId, period = 'day') => {
    let timeFrame;
    
    switch (period) {
      case 'week':
        timeFrame = 'DATE(p.start_time) >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)';
        break;
      case 'month':
        timeFrame = 'DATE(p.start_time) >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)';
        break;
      default: // day
        timeFrame = 'DATE(p.start_time) = CURDATE()';
    }
    
    const sql = `
      SELECT 
        COUNT(*) as total_pomodoros,
        SUM(CASE WHEN p.status = 1 THEN 1 ELSE 0 END) as completed_pomodoros,
        SUM(CASE WHEN p.status = 2 THEN 1 ELSE 0 END) as interrupted_pomodoros,
        SUM(CASE WHEN p.status = 1 THEN p.duration ELSE 0 END) as total_minutes,
        COUNT(DISTINCT p.task_id) as total_tasks
      FROM pomodoro_records p
      WHERE p.user_id = ? AND ${timeFrame}
    `;
    
    const results = await query(sql, [userId]);
    return results[0];
  }
};

module.exports = pomodoroModel; 